//
//  YBNormalSelectDeptViewController.m
//  GongXinDangJian
//
//  Created by apple on 17/12/26.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YBNormalSelectDeptViewController.h"

#import "YBSelectShareSingalData.h"

#import "YBAddPeopleSignalData.h"

#import "YBSelectDeptListTableViewCell.h"
#define DEPTID @"YBSelectDeptListTableViewCell"

#import "ZJSqlit.h"

#import "YBNormalShadowInputView.h"


@interface YBNormalSelectDeptViewController ()<UITableViewDelegate , UITableViewDataSource , YBNormalShadowInputViewDelegate>
@property (nonatomic , strong) NSArray * mainDeptArray;

@property (nonatomic , strong) UIScrollView * titleScrollView;

@property (nonatomic , strong) UITableView * tableView;

@property (nonatomic , strong) NSMutableArray * selectHeadArray;

@property (nonatomic , strong) NSMutableArray<UIButton *> * headButtonArray;

@property (nonatomic , strong) ZJSqlit * mySqlite;

@property (nonatomic , strong) YBNormalShadowInputView * itemInputView;

@end

@implementation YBNormalSelectDeptViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.titlelabel.text = @"选择单位";
    self.mainDeptArray = @[];
    [self ybInitMyView];
}

-(void)ybInitMyView{
    [self.view addSubview:self.titleScrollView];
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0 , navHeight + ItemHeight * 80 - 1 , [UIScreen zj_screenWith], 1)];
    lineView.backgroundColor = [UIColor themeGrayColor];
    [self.view addSubview:lineView];
    
    [self.view addSubview:self.tableView];
    
    NSArray * tempDeptArray = [NSArray yy_modelArrayWithClass:[YBSelectHeadModel class] json:[self.mySqlite getStringById:YBUSERDATAKEY fromTable:@"ORG_DEPTS"]];
    [self loadDataWithDeptArray:tempDeptArray];
    
    [self.view addSubview:self.itemInputView];
    
}




-(void)addHeadButtonWithHeadModel:(YBSelectHeadModel *)headModel{
    for (UIButton * tempButton in self.headButtonArray) {
        [tempButton setTitleColor:[UIColor textBlackColor] forState:UIControlStateNormal];
    }
    
    
    CGFloat buttonWidth = [headModel.NAME boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, ItemHeight * 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : LYPFONT(16)} context:nil].size.width;
    
    CGFloat beginX = 0.f;
    if (self.headButtonArray.count > 0) {
        beginX = CGRectGetMaxX(self.headButtonArray.lastObject.frame);
    }
    UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(beginX, 0, buttonWidth + ItemWidth * 60, ItemHeight * 80)];
    [button setTitleColor:[UIColor themeColor] forState:UIControlStateNormal];
    button.titleLabel.font = LYPFONT(16);
    [button setTitle:[ToolClass returnNoNullStringWithString:headModel.NAME] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"jiantou_r"] forState:UIControlStateNormal];
    button.tag = 300 + self.headButtonArray.count;
    
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, -ItemWidth * 44, 0, ItemWidth * 44)];
    [button setImageEdgeInsets:UIEdgeInsetsMake(0, buttonWidth, 0, -buttonWidth)];
    
    [button addTarget:self action:@selector(option_titleButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.titleScrollView addSubview:button];
    [self.headButtonArray addObject:button];
    [self.selectHeadArray addObject:headModel];
    [self.titleScrollView setupAutoContentSizeWithRightView:self.headButtonArray.lastObject rightMargin:ItemWidth * 5];
}


-(void)option_titleButton:(UIButton *)sender{
    if ([sender isEqual:self.headButtonArray.lastObject]) {
        return;
    }
    NSInteger index = sender.tag - 300;
    NSInteger totalCount = self.selectHeadArray.count - 1;
    for (NSInteger i = index + 1; i < self.selectHeadArray.count; i ++) {
        UIButton * button = self.headButtonArray[totalCount];
        [self.headButtonArray removeObject:button];
        [button removeFromSuperview];
        totalCount --;
    }
    self.selectHeadArray = [[self.selectHeadArray subarrayWithRange:NSMakeRange(0, index + 1)] mutableCopy];
    
    [self.titleScrollView setupAutoContentSizeWithRightView:self.headButtonArray.lastObject rightMargin:ItemWidth * 5];
    
    [self ybRestructureDataSourceWithModel:self.selectHeadArray.lastObject];
    
    [self.headButtonArray.lastObject setTitleColor:[UIColor themeColor] forState:UIControlStateNormal];
}


-(void)ybNormalShadowInputViewDidClickWithName:(NSString *)name{
    [self.itemInputView.inputTextField resignFirstResponder];
    if (self.delegate && [self.delegate respondsToSelector:@selector(ybNormalSelectDeptViewControllerDidSelectUnitWithName: unitId:)]) {
        [self.delegate ybNormalSelectDeptViewControllerDidSelectUnitWithName:name unitId:@""];
    }
    [self.navigationController popViewControllerAnimated:YES];
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ItemHeight * 80;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YBSelectDeptListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:DEPTID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.isChooseUnit = YES;
    cell.model = self.dataArray[indexPath.row];
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YBSelectHeadModel * model = self.dataArray[indexPath.row];
    if ([model.ID isEqualToString:@"qtdw123"]) {
        self.itemInputView.hidden = NO;
        self.itemInputView.inputTextField.text = @"";
        [self.itemInputView.inputTextField becomeFirstResponder];
    }
    else{
        if ([model.DEPT_LV integerValue] == 4) {
            //选择
            if (self.delegate && [self.delegate respondsToSelector:@selector(ybNormalSelectDeptViewControllerDidSelectUnitWithName: unitId:)]) {
                [self.delegate ybNormalSelectDeptViewControllerDidSelectUnitWithName:model.NAME unitId:model.ID];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
        else{
            //下一级
            [self addHeadButtonWithHeadModel:model];
            [self ybRestructureDataSourceWithModel:model];
        }
    }
}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}




- (UIScrollView *)titleScrollView{
    if (!_titleScrollView ) {
        _titleScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, navHeight, [UIScreen zj_screenWith], ItemHeight * 80)];
        _titleScrollView.showsVerticalScrollIndicator = NO;
        _titleScrollView.showsHorizontalScrollIndicator = NO;
        _titleScrollView.contentSize = _titleScrollView.size;
        _titleScrollView.backgroundColor = [UIColor whiteColor];
    }
    return _titleScrollView;
    
}


-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, navHeight + ItemHeight * 80, [UIScreen zj_screenWith], [UIScreen zj_screenHeight] - ItemHeight * 80 - navHeight) style:UITableViewStyleGrouped];
        [_tableView registerClass:[YBSelectDeptListTableViewCell class] forCellReuseIdentifier:DEPTID];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        [_tableView adaptiveIOS11];
        
    }
    return _tableView;
}


-(void)loadDataWithDeptArray:(NSArray *)deptArray
{
    NSMutableArray * tempDataArray = [NSMutableArray array];
    for (YBSelectHeadModel * model in deptArray) {
        if ([model.FID isEqualToString:@"0"] || [model.FID isEqualToString:@""]) {
            model.NAME = @"全部";
            [self addHeadButtonWithHeadModel:model];
            YBSelectHeadModel * otherModel = [[YBSelectHeadModel alloc]init];
            otherModel.NAME = @"其他单位";
            otherModel.DEPT_LV = @"4";
            otherModel.FID = model.ID;
            otherModel.ID = @"qtdw123";
            [tempDataArray addObjectsFromArray:deptArray];
            [tempDataArray addObject:otherModel];
            break;
        }
    }
    self.mainDeptArray = [tempDataArray copy];
    [self ybRestructureDataSourceWithModel:self.selectHeadArray.lastObject];
}

-(void)ybRestructureDataSourceWithModel:(YBSelectHeadModel *)model{
    [self.dataArray removeAllObjects];
    [self.headArray removeAllObjects];
    for (YBSelectHeadModel * deptModel in self.mainDeptArray) {
        if ([deptModel.FID isEqualToString:model.ID]) {
            [self.dataArray addObject:deptModel];
        }
    }
    [self.tableView reloadData];
}



-(NSMutableArray *)selectHeadArray
{
    if (!_selectHeadArray) {
        _selectHeadArray = [NSMutableArray array];
    }
    return _selectHeadArray;
}


-(NSMutableArray<UIButton *> *)headButtonArray
{
    if (!_headButtonArray) {
        _headButtonArray = [NSMutableArray array];
    }
    return _headButtonArray;
}

-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


-(NSMutableArray *)headArray
{
    if (!_headArray) {
        _headArray = [NSMutableArray array];
    }
    return _headArray;
}

-(ZJSqlit *)mySqlite
{
    if (!_mySqlite) {
        _mySqlite = [[ZJSqlit alloc]init];
    }
    return _mySqlite;
}

-(YBNormalShadowInputView *)itemInputView
{
    if (!_itemInputView) {
        _itemInputView = [[YBNormalShadowInputView alloc]initWithTitle:@"其他单位"];
        _itemInputView.maxLength = 50;
        _itemInputView.noticeString = @"不能为空";
        _itemInputView.hidden = YES;
        _itemInputView.delegate = self;
    }
    return _itemInputView;
}

@end
